package com.ssy.lingxi.message.websocket.util;

import cn.hutool.json.JSONUtil;
import com.ssy.lingxi.message.websocket.model.WsMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

/**
 * webSocket发送消息工具
 * @author yzc
 * @version 2.0.0
 * @date 2020/11/2
 */
@Slf4j
public class MessageUtil {

    private MessageUtil() {
    }

    /**
     * 真正发送消息
     * @param session
     * @param message
     */
    public static void sendMessage(WebSocketSession session, WsMessage message) {
        if (session == null || !session.isOpen()) {
            log.error("webSocketSession is null or is not open");
            return;
        }

        TextMessage textMessage = new TextMessage(JSONUtil.toJsonStr(message));
        try {
            session.sendMessage(textMessage);
        } catch (IOException e) {
            log.error("session send message error, text: {}", textMessage, e);
        }
    }
}
